package eu.games.esmi.ieat.indicatorvalues.data;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import com.vaadin.addon.timeline.Timeline;
import com.vaadin.data.Container;
import com.vaadin.data.util.IndexedContainer;
import it.polimi.games.epkb.controller.ThresholdsJpaController;
import it.polimi.games.epkb.entityClasses.StoredValues;
import it.polimi.games.epkb.entityClasses.Thresholds;
import it.polimi.games.epkb.entityClasses.ThresholdsPK;
import java.math.BigDecimal;
import java.util.List;
import java.util.ListIterator;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class GPIValues implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -8999628917463544221L;
    public static final int GREEN = 0;
    public static final int YELLOW = 1;
    public static final int RED = 2;
    public static final int GRAY = 3;
    
    public static Container.Indexed getValues() {  // random numbers generator

        IndexedContainer values = new IndexedContainer();
        values.addContainerProperty(Timeline.PropertyId.VALUE, Float.class, new Float(0));
        values.addContainerProperty(Timeline.PropertyId.TIMESTAMP, java.util.Date.class, null);

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(System.currentTimeMillis()));
        Float v;
        for (int i = 0; i < 1000; i++) {

            cal.add(Calendar.MINUTE, i);

            v = new Float(Math.random() * 100);


            Object key = values.addItem();
            values.getItem(key).getItemProperty(Timeline.PropertyId.VALUE).setValue(v);
            values.getItem(key).getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(cal.getTime());

            //System.out.println(cal.getTime().toString() + " "  + v);
        }

        return values;

    }

    public static Container.Indexed getValues(List<StoredValues> storedvalues, String idComponent, String idGpiKpi) {

        IndexedContainer values = new IndexedContainer();
        values.addContainerProperty(Timeline.PropertyId.VALUE, Float.class, new Float(0));
        values.addContainerProperty(Timeline.PropertyId.TIMESTAMP, java.util.Date.class, null);

        //Calendar cal = Calendar.getInstance();
        //cal.setTime(new Date(System.currentTimeMillis()));
        Float v;

        ListIterator i = storedvalues.listIterator(storedvalues.size());

        while (i.hasPrevious()) {

            StoredValues sv = (StoredValues) i.previous();

            if (sv.getIdGPIKPI().getId().equals(idGpiKpi) && sv.getIdComponent().getId().equals(idComponent)) {

                //System.out.println(sv.getIdGPIKPI() + " - " + sv.getComputedValue() + " - " + sv.getDefinitionTime().toString());

                Object key = values.addItem();
                values.getItem(key).getItemProperty(Timeline.PropertyId.VALUE).setValue(sv.getComputedValue());
                values.getItem(key).getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(sv.getDefinitionTime());

                //System.out.println(cal.getTime().toString() + " "  + v);
            }
        }

        return values;

    }

    public static Container.Indexed getAvgValues(List<Object[]> storedvalues, String idComponent, String idGpiKpi) {

        IndexedContainer values = new IndexedContainer();
        values.addContainerProperty(Timeline.PropertyId.VALUE, Float.class, new Float(0));
        values.addContainerProperty(Timeline.PropertyId.TIMESTAMP, java.util.Date.class, null);

        //Calendar cal = Calendar.getInstance();
        //cal.setTime(new Date(System.currentTimeMillis()));
        Float v;

        ListIterator i = storedvalues.listIterator(storedvalues.size());

        while (i.hasPrevious()) {

            Object[] o = (Object[]) i.previous();
            
            AvgValues sv = new AvgValues(((Long)o[0]), ((BigDecimal)o[1]));

//            if (sv.getIdGPIKPI().getId().equals(idGpiKpi) && sv.getIdComponent().getId().equals(idComponent)) {

               //System.out.println((Long)o[0] + " - " + idGpiKpi + " - " + sv.getComputedValue() + " - " + sv.getDefinitionTime().toString());

            Object key = values.addItem();
            values.getItem(key).getItemProperty(Timeline.PropertyId.VALUE).setValue(sv.getComputedValue());
            values.getItem(key).getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(sv.getDefinitionTime());

            //System.out.println(cal.getTime().toString() + " "  + v);
            //         }
        }

        //System.out.println("size " + values.size());
        
        return values;

    }

    public static int getStatus(List<StoredValues> storedvalues, String idComponent, String idGpiKpi) {

        Date current = null;
        int result = GPIValues.GREEN;

        ListIterator i = storedvalues.listIterator(storedvalues.size());

        while (i.hasPrevious()) {

            StoredValues sv = (StoredValues) i.previous();

            //System.out.println(sv.getIdGPIKPI() + " - " + sv.getComputedValue() + " - " + sv.getDefinitionTime().toString());

            if (sv.getIdGPIKPI().getId().equals(idGpiKpi) && sv.getIdComponent().getId().equals(idComponent)) {



                if (current != null) {

                    if (current.before(sv.getDefinitionTime())) {
                        current = sv.getDefinitionTime();
                        if (sv.getRed()) {
                            result = GPIValues.RED;
                        } else if (sv.getYellow()) {
                            result = GPIValues.YELLOW;
                        } else {
                            result = GPIValues.GREEN;
                        }
                    }

                } else {
                    sv.getDefinitionTime();
                    if (sv.getRed()) {
                        result = GPIValues.RED;
                    } else if (sv.getYellow()) {
                        result = GPIValues.YELLOW;
                    } else {
                        result = GPIValues.GREEN;
                    }
                }


            }
        }

        return result;

    }

    public static int getAvgStatus(List<Object[]> storedvalues, String idComponent, String idGpiKpi) {

        Date current = null;
        int result = GPIValues.GREEN;

        ListIterator i = storedvalues.listIterator(storedvalues.size());
            result = GPIValues.GRAY;

//        while (i.hasPrevious()) {
//
//            Object[] o = (Object[]) i.previous();
//            
//            AvgValues sv = new AvgValues(((Double)o[0]), ((BigDecimal)o[1]));
//
//            System.out.println(idComponent + " - " + idGpiKpi + " - " + sv.getDefinitionTime().toString() + " - " + sv.getComputedValue());
//            
//            //if (sv.getIdGPIKPI().getId().equals(idGpiKpi) && sv.getIdComponent().getId().equals(idComponent)) {
//
//            //sv.setRed(isRed(idComponent, idGpiKpi, sv.getComputedValue()));
//            //sv.setYellow(isYellow(idComponent, idGpiKpi, sv.getComputedValue()));
//
//
//            if (current != null) {
//
//                if (current.before(sv.getDefinitionTime())) {
//                    current = sv.getDefinitionTime();
//                    if (sv.getRed()) {
//                        result = GPIValues.RED;
//                    } else if (sv.getYellow()) {
//                        result = GPIValues.YELLOW;
//                    } else {
//                        result = GPIValues.GREEN;
//                    }
//                }
//
//            } else {
//                sv.getDefinitionTime();
//                if (sv.getRed()) {
//                    result = GPIValues.RED;
//                } else if (sv.getYellow()) {
//                    result = GPIValues.YELLOW;
//                } else {
//                    result = GPIValues.GREEN;
//                }
//            }


            //}
//        }

        return result;

    }

    private static boolean isRed(String componentID, String gpiKpiID, BigDecimal value) {
        boolean res;
        
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);
                
        ThresholdsPK tPK = new ThresholdsPK();
        tPK.setIdComponent(componentID);
        tPK.setIdGPIKPI(gpiKpiID);
        Thresholds t = thresholdsCtrl.findThresholds(tPK);

        if ((value.compareTo(t.getEmergencyRangeHigh()) == 1) || (value.compareTo(t.getEmergencyRangeLow()) == -1)) {
            res = true;
        } else {
            res = false;
        }
        
        emf.close();
        return res;
    }

    private static boolean isYellow(String componentID, String gpiKpiID, BigDecimal value) {

        boolean res;
        
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);

        ThresholdsPK tPK = new ThresholdsPK();
        tPK.setIdComponent(componentID);
        tPK.setIdGPIKPI(gpiKpiID);
        Thresholds t = thresholdsCtrl.findThresholds(tPK);

        if (((value.compareTo(t.getNormalRangeHigh()) == 1) & (value.compareTo(t.getEmergencyRangeHigh()) == -1)) || ((value.compareTo(t.getNormalRangeLow()) == -1) & (value.compareTo(t.getEmergencyRangeLow()) == 1))) {
            res = true;
        } else {
            res = false;
        }
        emf.close();
        return res;
    }

    public static BigDecimal getNrl(String idComponent, String idGpiKpi) {


        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);


        ThresholdsPK pk = new ThresholdsPK(idGpiKpi, idComponent);

        Thresholds t = thresholdsCtrl.findThresholds(pk);

        emf.close();

        return t.getNormalRangeLow();

    }

    public static BigDecimal getNrh(String idComponent, String idGpiKpi) {


        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);


        ThresholdsPK pk = new ThresholdsPK(idGpiKpi, idComponent);

        Thresholds t = thresholdsCtrl.findThresholds(pk);

        emf.close();

        return t.getNormalRangeHigh();

    }

    public static BigDecimal getErl(String idComponent, String idGpiKpi) {


        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);


        ThresholdsPK pk = new ThresholdsPK(idGpiKpi, idComponent);

        Thresholds t = thresholdsCtrl.findThresholds(pk);

        emf.close();

        return t.getEmergencyRangeLow();

    }

    public static BigDecimal getErh(String idComponent, String idGpiKpi) {


        EntityManagerFactory emf = Persistence.createEntityManagerFactory(EMF.PU_NAME);

        ThresholdsJpaController thresholdsCtrl = new ThresholdsJpaController(emf);


        ThresholdsPK pk = new ThresholdsPK(idGpiKpi, idComponent);

        Thresholds t = thresholdsCtrl.findThresholds(pk);

        emf.close();

        return t.getEmergencyRangeHigh();

    }
}